import {observable, action, toJS} from 'mobx';
import {Tools,ListView,Toast} from 'weaver-mobile';
import * as Api from '../../api/news';
import * as SystemDocApi from '../../api/systemdoc';
import { SearchAdvanced,Form,SearchPage,ListViewPage  } from 'weaver-mobile-page';
const getLabel = Tools.getLabel;

export default class NewsStore {
  @observable newsType = [];
  @observable conditions = [];
  @observable newsList = [];
  @observable newsListViewPageStore; 
  @observable newsSearchListViewPageStore;
  @observable typeId = '';//当前选中的tabid
  @observable typeIdindex = '';//当前选中的tabid的index
  @observable current = 1;
  @observable scope = -1;
  @observable elliVisible = false;
  @observable inited = false;
  @observable imgData = []; //用来存储列表前五张图片，展示在轮播图上
  @observable myTag = []; //我的栏目包含的列（用于前台展示）
  @observable myTagBack = []; //我的栏目包含的列(用于数据操作)
  @observable moreTag = []; //更多栏目包含的列
  @observable moreTagBack = []; //更多栏目包含的列(用于数据操作)
  @observable moreTagColumnid = []; 
  @observable myTagColumnid = [];
  @observable carouselDocsub = ''; //当前轮播图的标题
  @observable isshow = false; //判断tag标签设置是否显示
  @observable ischange = true;// 判断当前是否是栏目编辑状态 true 编辑  false  完成
  @observable editspan = "";
  @observable clicktagspan = "";
  @observable carouselLocation = 0;//轮播图的定位点
  @observable searchPage;  
  @observable cloumnNoData = false; //判断当前的新闻column是否为空  
  @observable cloumnShowtype = "1"; //判断当前的新闻column的展示类型  1，为新闻模式，展示图片，2 为文档模式，不展示图片

  
  
  // 高级搜索
  @observable newsSearchAdDatasource = new ListView.DataSource({
    rowHasChanged: (row1, row2) => row1 !== row2,
  });
  @observable searchResult = [];
  @observable searchAd;
  @observable form = new Form.Store();
  @observable searchAdParams= {
    pageNum: 1,
  };
  @observable currentNum = 0;
  @observable showcarousel = true;
  searchInited = false;
  searchType = 6;  //搜索类型
  searchKey = {};  //搜索条件

  // @observable searchAdvancedBasicStore = new SearchAdvanced.Store({ route: '/systemdoc/searchAdvance' }); 

  
  @action
  init = (scope) => {
    this.scope = scope;
    this.newsListViewPageStore = new ListViewPage.Store({ route: `/news/${scope}` })
    this.newsSearchListViewPageStore = new ListViewPage.Store({ route: `/news/${scope}/newsSearch` });
    this.searchAd = new SearchAdvanced.Store({route: `/news/${scope}/newsSearch/advance`});
    this.searchPage = new SearchPage.Store({ route: `/news/${scope}/newsSearch/history`});
    this.elliVisible = false;
    this.getNewsType({scope});
    // this.setSearchHistory();
    SystemDocApi.init().then((result) => {
      this.conditions = result.conditions;
    });
    this.inited = true;
  }
  //将已经阅读过的设置已阅，取消阅读标识
  setDocIsNew = (docid) =>{
    this.newsListViewPageStore.data.map((val)=>{
      if(val.docid===docid){
        val.isnew = '0';
      }
      return val;
    })
    this.newsListViewPageStore.updateDataSource();
  }
  setDocSearchNew= (docid) =>{
    this.newsSearchListViewPageStore.data.map((val)=>{
      if(val.docid===docid){
        val.isnew = '0';
      }
      return val;
    })
    this.newsSearchListViewPageStore.updateDataSource();
  }
  //清空数据，切换tab时，回到顶部
  ListBackTop = () =>{
    this.newsList = [];
    this.newsListViewPageStore.setState({
      loading: true,
      data: toJS(this.newsList),
      isTable: false,
      hasMore: true,
      refreshLoading:false,
    });
    this.newsListViewPageStore.updateDataSource();
  }
  //设置轮播图的定位点
  setCarouselLocation = () =>{
    this.carouselLocation = 0;
  }
  //更新当前选中轮播图的标题
  updateCarouselDocsub = (docsubject, index ) => {
    this.carouselDocsub = docsubject;
    this.carouselLocation = index;
  }
//当前选中的tabid
  setChooseTabid = (tabInfo,index) =>{
    //重置高级搜索浏览框
    this.searchAd.form.resetFields();
    this.typeId = tabInfo.columnid || tabInfo.id;
    this.cloumnShowtype = tabInfo.showtype;
    this.typeIdindex = index;
  }
  // inittag()

//移除我的栏目(前台展示)
  newstagRemove = (index,data) =>{
    this.moreTag.push(data);
    let operaterMytag = toJS(this.myTag)
    operaterMytag.splice(index,1);
    this.myTag = operaterMytag
  }
  /**
   * 移动标签，拖动到某个节点上时触发（不用松开就会触发）
   * @param id 拖拽id
   * @param overId 拖拽覆盖的id
   */
  moveTag = (id, overId) => {
    let list = toJS(this.myTag);
    let moveIndex = 0;
    let dragItem = null;
    let overIndex = -1;
    // 调整拖动的顺序
    list = list.map((item, index) => {
      // 找到拖拽的节点
      if (id === item.columnid) {
        moveIndex = moveIndex + 1;// 在拖拽节点之后的前移一位
        dragItem = item;
        if (overIndex > -1) {// 如果拖拽节点在覆盖节点之后，则需要特殊处理，返回前一条数据
          return list[index - 1];
        }
      } else if (overId === item.columnid) {
        moveIndex = moveIndex - 1;// 在覆盖节点之后的要后移一位
        overIndex = index;
        return null;
      }
      return list[index + moveIndex];
    })
    list[overIndex] = dragItem;// 将拖拽节点放到覆盖节点的位置

    this.myTag = list;
  }
//新增我的栏目(前台展示)
  newstagAdd  = (index,data) =>{
    this.myTag.push(data);
    let operaterMoreTag = toJS(this.moreTag);
    operaterMoreTag.splice(index,1);
    this.moreTag = operaterMoreTag;
    if(this.ischange){
      this.myTagBack = [];
      this.myTagBack = this.myTag;
      let operaterMoreTagBack = toJS(this.moreTagBack);
      operaterMoreTagBack.splice(index,1);
      this.moreTagBack = operaterMoreTagBack;
    }
  }
  //判断是否展示栏目页面
  newstagisshow = () =>{
    this.isshow = !this.isshow;
    //点击完关闭栏目，立刻判断当前tab标签是否更新
    if(!this.isshow){
      // this.getNewsType({scope:this.scope});
      let moretagtwins = [];
      let mytagtwins = [];
      for(let i = 0;i<this.myTagBack.length;i++){
        mytagtwins[i] = this.myTagBack[i];
      }
      for(let i = 0;i<this.moreTagBack.length;i++){
        moretagtwins[i] = this.moreTagBack[i];
      }
      this.moreTag = moretagtwins;
      this.myTag = mytagtwins;
      this.newsType = [];
      for(let i=0;i<this.myTagBack.length;i++){
        if(this.myTagBack[i]!==undefined){
          this.newsType.push({id: this.myTagBack[i].columnid, key: this.myTagBack[i].columnid, title: this.myTagBack[i].columnname})
        }
      }
      //判断当前被选中的typeid是否被移除,如果被移除，设置第一个为选中
      let flag = false;
      // let choosetab = 0
      for(let i = 0;i<this.newsType.length;i++){  
        if(toJS(this.typeId) === toJS(this.newsType[i].key)){
          flag = true;
          this.typeIdindex = i;
          break;
        }
      }
      if(!flag){
        this.typeIdindex = 0;
        this.typeId = this.newsType[0] ? this.newsType[0].key : '';
        this.getNews(this.typeId)
      }
    }
    if(!this.ischange){
      this.ischange = !this.ischange;
      this.editspan = this.ischange ? getLabel(388752, '排序删除') : getLabel(555, '完成');
      this.clicktagspan = this.ischange ? getLabel(388751, '点击进入栏目') : getLabel(388759, '长按拖动排序');
    }
  }
  //判断是否编辑我的栏目
  newstagedit = () =>{
    this.ischange = !this.ischange;
    this.editspan = this.ischange ? getLabel(388752, '排序删除') : getLabel(555, '完成');
    this.clicktagspan = this.ischange ? getLabel(388751, '点击进入栏目') : getLabel(388759, '长按拖动排序');
  }
   //保存移除操作的更多栏目 (后台数据操作)
   saveMovetagedit = () =>{
    //清空数组，否则可能会出错
    this.moreTagColumnid = [];
    this.myTagColumnid = [];

    let ans = 0
    for(let i = 0; i < this.moreTag.length; i++){
      this.moreTagColumnid[ans++] = this.moreTag[i].columnid;
    }
    let ant = 0;
    for(let i =0; i < this.myTag.length; i++){
      if(this.myTag[i])
      this.myTagColumnid[ant++] = this.myTag[i].columnid;
    }
    //设置不可以全部移除
    if(ant===0){
      // this.myTagBack = this.myTag;
      Toast.fail(getLabel(388760, '不能全部删除'), 1);
      return 
    }
    let moretagtwins = [];
    let mytagtwins = [];
    let j = 0;
    for(let i = 0;i<this.myTag.length;i++){
      if(this.myTag[i])
      mytagtwins[j++] = this.myTag[i];
    }
    for(let i = 0;i<this.moreTag.length;i++){
      if(this.moreTag[i])
      moretagtwins[i] = this.moreTag[i];
    }

    this.myTag = mytagtwins;
    this.moreTagBack = moretagtwins;
    this.myTagBack = mytagtwins;

    //移除操作，保存的时候需要将我的栏目和更多栏目一起保存
    this.saveMoveMoreTag(toJS(this.moreTagColumnid));
    this.saveAddMyTagColumn(toJS(this.myTagColumnid));
    //获取当前被选中的tab标签的数据
   
  }
  //添加我的栏目tag(只对从更多到我的 的tag的状态进行更新)(后台数据操作)
  updateAddMyTagstatus = (tabColumnInfo) => {
    // 更新tab页标签
    this.newsType.push({id: tabColumnInfo.columnid, key: tabColumnInfo.columnid, title: tabColumnInfo.columnname})
    Api.updateAddMyTagstatus({column:tabColumnInfo.columnid, scope: this.scope})
    this.cloumnNoData = false;
  }
  //保存移除我的栏目(后台数据操作)
  saveMoveMoreTag = (columnsMoreid)=>{
    if(this.moreTagColumnid.length>0){
       Api.saveMoveMoreTag({columnsMore:columnsMoreid, scope: this.scope})
    }
  }
  //保存添加我的栏目(后台数据操作)
  saveAddMyTagColumn = (columnsid)=>{
    Api.saveAddMyTagColumn({columns:columnsid, scope: this.scope})
  }
  //获取新闻的类型
  getNewsType = (params) => {
    return Api.getNewsType(params).then((result) => {
      this.myTag = [];
      this.moreTag = [];
      this.myTagBack = [];
      if (!result.columns || result.columns.length === 0) {
        this.cloumnNoData = true;
        return;
      }else{
        this.cloumnNoData = false;
      }
      this.newsType = result.columns.map((item,index) => {
        return {id: item.columnid, key: item.columnid, title: item.columnname,showtype:item.showtype};
      });
      if (this.newsType.length > 0) {
        //获取我的栏目
        this.myTag = result.columns;
        this.myTagBack = result.columns;
        //获取当前被选中的tab标签的数据
        if(this.typeId === ''){
          this.typeId = result.columns[0].columnid;
          this.cloumnShowtype = result.columns[0].showtype;
          this.typeIdindex = 0;
        }
        this.getNews(this.typeId);
      }
      //获取更多栏目
      this.moreTag = result.columnsMore;
      this.moreTagBack = result.columnsMore;
    });
  }
  //下拉刷新
  refreshLoading = (typeId, current) =>{
    this.newsListViewPageStore.setState({refreshLoading:this.current<=1})
    this.getNews(typeId, current);
  }
  getNews = (typeId, current) => {
    this.newsListViewPageStore.setState({loading: true});
    this.typeId = typeId;
    this.current = current || 1;
    Api.getNews({columnid: typeId, current, scope: this.scope}).then((result) => {
      this.cloumnShowtype = result.showtype;
      //第二次进入
      if (current && current > 1) {
        this.newsList = [...toJS(this.newsList),...result.list];
      } else {
        this.newsList = result.list;
        let ans = 0;
        let imgDataTwins = [];
        for(let key in result.list){
          imgDataTwins[ans++] = result.list[key];
          if(ans>=5){
              break;
          }
        }
        this.imgData = imgDataTwins;
        if(this.imgData[0]!==undefined){
          this.carouselDocsub = this.imgData[0].docsubject;
        }else{
          this.carouselDocsub = '';
        }
      }
      
      this.newsListViewPageStore.setState({
        loading: false,
        data: toJS(this.newsList),
        isTable: false,
        hasMore: result && result.list.length > 0,
      });
      this.newsListViewPageStore.updateDataSource();
      if(!result.api_status){
        Toast.fail(getLabel(388768, '加载失败'),3)
      }

    });
  }
  setElliVisible = (visible) => {
    this.elliVisible = !this.elliVisible;
  }
  

  /**
   * 搜索新闻列表（第一页）
   * @returns {*}
   */
  searchNews = (params) => {
    this.searchKey = params ? params : {};
    this.searchAdParams = {
      //form参数:表单 store, 请求接口后生成，formParams：表单域的键值对
      ...(this.searchAd.form ? this.searchAd.form.formParams : {}),
      pageNum: 0
    };
    //将高级搜索的标题带到搜索框中
    this.searchKey.keyword = this.searchKey.keyword?this.searchKey.keyword:(this.searchAdParams?this.searchKey = {keyword:this.searchAdParams.docsubject,bySearch : this.searchAdParams.docsubject ? 1 : 0}:'');
    if(this.searchKey.bySearch === 1){
      //将历史搜索带带到搜索参数中
      this.searchAdParams  = {...this.searchAdParams,docsubject:this.searchKey.keyword }
    }
    this.searchResult = [];
    !this.searchInited && (this.searchInited = true);// 保证组件只初始化一次
    this.searchNewsNext().then(()=>{
      if(this.searchKey.bySearch === 1){
        this.addHistory(this.searchKey.keyword); 
      }else{
        this.setSearchHistory();
      }
    });
  }
  
  /**
   * 搜索新闻列表（下一页）
   * @returns {*}
   */
  searchNewsNext = () => {
    this.searchAdParams.pageNum++;
    return this.searchNewsByParams();
  }
  /**
   * 搜索新闻列表（实际调用接口与处理逻辑）
   * @returns {PromiseLike<T> | Promise<T> | *}
   */
  searchNewsByParams = () => {
    this.newsSearchListViewPageStore.setState({loading:true});
    this.newsSearchListViewPageStore.setState({refreshLoading:(this.searchAdParams.pageNum<=1)})
    return Api.searchNews({...this.searchAdParams,current:this.searchAdParams.pageNum,columnid: this.typeId,scope: this.scope}).then((result) => {
      this.searchResult = [...toJS(this.searchResult),...result.list];
      //搜索页面
      this.newsSearchListViewPageStore.setState({
        loading: false,
        data: toJS(this.searchResult),
        isTable: false,
        hasMore: result && result.list.length > 0,
      });
      this.newsSearchListViewPageStore.updateDataSource();
    });
  }
  
  //将搜索框中的信息带到高级搜索框中
  updateSearchDocSubject = (value) => {
    this.searchAd.form.updateField('docsubject', value);
  }

  //添加搜索历史
  addHistory = (keyword) =>{
    Api.addHistory({searchtext:keyword,type:this.searchType}).then(()=>{
      this.getHistory();
    })
  }
  //获取搜索历史
  getHistory = () => {
    const params = {type : this.searchType}; 
    Api.getHistoryList(params).then((result) => {
        this.historyList = [];
        result.historyData.map((data,i)=>{
          return this.historyList.push({
            key : i,
            name : data,
          });
        });
        this.searchPage.list.setState({data : this.historyList});
    }); 
  }
  //初始化搜索历史
  setSearchHistory = () => {
    const template = {
      default: [
        {
          key: 'col1',
          configs: [
            {
              key: 'col1_row1',
              configs: [
                { key: 'name' },
              ],
            },
          ],
        },
      ],
    };
    this.searchPage.setState({ template });
    this.getHistory();
  }
    //搜索
  doSearchByKeyword = (keyword) => {
    this.searchNews({keyword : keyword,bySearch : keyword ? 1 : 0}); 
    this.updateSearchDocSubject(keyword);
  }
  //清空搜索历史
  clearSearchHistory = () => {
    const params = {type : this.searchType};
    Api.clearSearchHistory(params).then((result) => {
        this.historyList = [];
        this.searchPage.list.setState({data : this.historyList}); 
    }); 
  }
}